package com.whros.helloworld;

import com.whros.helloword.plugin.PluginInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.net.MalformedURLException;
import java.util.List;

/**
 * @author whroid
 * @since 2021-07-25
 */
public class PluginConfigMonitor {

    private FileAlterationMonitor fileMonitor;

    PluginManager pluginManager;

    public void init(String confDir, PluginManager pluginManager){
        this.pluginManager = pluginManager;
        try {
            FileAlterationObserver observer = new FileAlterationObserver(confDir,
                    FileFilterUtils.and(FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter("jar")));
            FileListener listener = new FileListener();
            observer.addListener(listener);
            fileMonitor = new FileAlterationMonitor(3000, observer);
            fileMonitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class FileListener extends FileAlterationListenerAdaptor {

        @Override
        public void onFileCreate(File file) {
            super.onFileCreate(file);
            System.out.println("onFileCreate:"+file.getName());
            try {
                List<PluginInfo> pluginInfoList = PluginLoader.loadPlugin(file.getAbsolutePath());

                if(CollectionUtils.isEmpty(pluginInfoList)){
                    return;
                }

                pluginInfoList.forEach( pluginInfo -> {
                    pluginManager.addPlugin(pluginInfo);
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFileChange(File file) {
            super.onFileChange(file);
            System.out.println("onFileChange:"+file.getName());
        }

        @Override
        public void onFileDelete(File file) {
            super.onFileDelete(file);
            System.out.println("onFileDelete:"+file.getName());
        }
    }
}
